package org.example.util;

import cn.hutool.core.lang.Dict;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import com.aliyun.oss.ServiceException;
import com.lowagie.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
public class PDFUtil {

    private static final String TEMPLATE_PATH = "template/ftl";
    public static void exportHtmlToPdf() {
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            setContentType(response, "测试html转pdf", FileType.PDF);
            // 获取HTML模板引擎
            TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig(TEMPLATE_PATH, TemplateConfig.ResourceMode.CLASSPATH));
            // 加载HTML模板文件
            Template template = engine.getTemplate("test.html");

            // 创建数据字典，用于填充模板中的变量
            Dict dict = Dict.create();
            dict.set("name", "测试导出模版标题");
            dict.set("meetingDate", "2024");
            dict.set("address", "广东省深圳市");
            dict.set("compereName", "哈哈哈公司");
            dict.set("lastTempDays", 1);
            dict.set("lastRainDays", 2);
            dict.set("lastWindDays", 3);
            dict.set("lastMeetingType", "上周");
            // 设置模板内容，此处为富文本内容
            dict.set("content", "<span style='color: #ff0000;'>测试模版内容哈</span>");
            // 渲染模板，生成HTML字符串
            String html = template.render(dict);
            try (ByteArrayOutputStream byteOs = new ByteArrayOutputStream()) {
                // 创建 ITextRenderer 对象用于HTML到PDF的转换
                ITextRenderer renderer = new ITextRenderer();
                // 获取字体解析器，以便添加中文字体支持
                ITextFontResolver fontResolver = (ITextFontResolver) renderer.getSharedContext().getFontResolver();
                // 添加中文字体，为了在PDF中支持中文显示
                fontResolver.addFont(getFontPath("FangSong_GB2312",Boolean.TRUE), "FangSong_GB2312", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, "");
                fontResolver.addFont(getFontPath("simsun",Boolean.FALSE), "Song", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, "");
                // 设置为文档内容
                renderer.setDocumentFromString(html);
                // 布局文档
                renderer.layout();
                renderer.createPDF(byteOs);
                renderer.finishPDF();
                try (ServletOutputStream os = response.getOutputStream()) {
                    os.write(byteOs.toByteArray());
                    os.flush();
                }
            }
        } catch (IOException e) {
            log.error("html转pdf异常：" + e.getMessage());
            throw new ServiceException("html转pdf异常：" + e.getMessage());
        }
    }

    private static String getFontPath(String fontName, Boolean isTTF) {
        if (isTTF)
            return "/font/" + fontName + ".ttf";
        else
            return "/font/" + fontName + ".ttc";
    }

    public static void setContentType(HttpServletResponse response, String fileName, FileType fileType) {
        try {
            // 设置响应内容的编码格式为UTF-8
            response.setCharacterEncoding("UTF-8");
            // 根据文件类型设置响应的内容类型
            response.setContentType(fileType.getDesc());
            // 设置响应头，指定文件下载时的文件名和文件类型
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8") + fileType.getType());
        } catch (UnsupportedEncodingException e) {
            // 当文件名编码失败时，抛出自定义异常
            throw new RuntimeException("设置ContentType失败: " + e.getMessage());
        }
    }
}
